﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using GenaralLibs;
using System.Threading;
using System.Runtime.InteropServices;
using System.Data.SqlClient;
using CustomControls;
using System.Text.RegularExpressions;
using Lists;
using System.IO;
using Security;

namespace QLKDMain.HoSo
{
    public partial class FrmHoSoKemTieuThuc : FrmBase
    {
        #region RequestAddNew event and delegate
        public delegate void OnRequestAddNew();
        /// <summary>
        /// Occur whenever this voucher is modified: added new, deleted, updated
        /// </summary>
        /// <param name="?"></param>
        /// <returns></returns>
        public event OnRequestAddNew RequestAddNew;
        #endregion

        protected HoSoDangKy _HoSoDangKy;
        protected DateTime lastRequestTime;
        protected EditState _EditState = EditState.Undefined;
        WebCam webcam;

        public FrmHoSoKemTieuThuc()
        {
            InitializeComponent();
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            try
            {
                switch (keyData)
                {
                    //case Keys.F2:
                    //    AddNew();
                    //    return true;
                    //    break;
                    //case Keys.F4:
                    //    Edit();
                    //    return true;
                    //    break;
                    //case Keys.F5:
                    //    Save();
                    //    return true;
                    //    break;
                    default:
                        return base.ProcessCmdKey(ref msg, keyData);
                        break;
                }
            }
            catch (Exception ex)
            {
                GenaralLibs.FrmExceptionNotifier.ShowAndLog(ex);
                return false;
            }
        }

        protected virtual void SetEditState(EditState editState)
        {
            _EditState = editState;
            base.SetEditState(editState);
            switch (editState)
            {
                case EditState.CreatingNew:
                case EditState.Modifying:
                    btnQuanLyFile.Enabled = true;
                    btnMoAnhBangDuongDan.Enabled = true;
                    btnChupAnh.Enabled = true;
                    btnQuanLyFile.Enabled = true;
                    break;
                case EditState.LuuGoc:
                    btnQuanLyFile.Enabled = true;
                    btnMoAnhBangDuongDan.Enabled = false;
                    btnChupAnh.Enabled = false;
                    btnQuanLyFile.Enabled = false;
                    break;
                case EditState.LuuTam:
                    btnLuuGoc.Enabled = false;
                    btnQuanLyFile.Enabled = true;
                    btnMoAnhBangDuongDan.Enabled = false;
                    btnChupAnh.Enabled = false;
                    btnQuanLyFile.Enabled = false;
                    break;
                case EditState.NgungCapPhep:
                    btnLuuGoc.Enabled = false;
                    btnQuanLyFile.Enabled = false;
                    btnMoAnhBangDuongDan.Enabled = false;
                    btnChupAnh.Enabled = false;
                    btnQuanLyFile.Enabled = false;
                    break;
            }

            gridViewDs.OptionsBehavior.Editable = false;
        }
        protected void SetNumberDisplayFormat()
        {
            foreach (Control control in this.Controls)
            {
                if (control is DevExpress.XtraEditors.TextEdit)
                {
                    if ((control as DevExpress.XtraEditors.TextEdit).Properties.DisplayFormat.FormatType == DevExpress.Utils.FormatType.Numeric)
                    {
                        FrmBase.FormatTextEdit(control as DevExpress.XtraEditors.TextEdit, TextFormatType.Money);
                    }
                }
                else if (control is DevExpress.XtraGrid.GridControl)
                {
                    FrmBase.FormatNumberInGridView((control as DevExpress.XtraGrid.GridControl).MainView as DevExpress.XtraGrid.Views.Grid.GridView);
                }
            }
        }

        protected void Edit()
        {
            //if (_EditState == EditState.Modifying)
            //{
            //    MessageBox.Show("Đã có hồ sơ ở trạng thái sửa\nCần lưu trước khi sửa hồ sơ mới");
            //    return;
            //}
            SetEditState(EditState.Modifying);
            try
            {
                DataRow row = gridViewDs.GetFocusedDataRow();
                _HoSoDangKy = DanhMucHoSoDangKy.Instance.GetByID((int)row["ID"]);

                nmrSTTHoSo.Text = _HoSoDangKy.SoTT.ToString();
                txtSoHoSo.EditValue = _HoSoDangKy.SoHoSo;
                User userCreate = UserList.Instance.GetByID(_HoSoDangKy.CanBoCapID);
                if (userCreate != null) txtCanBo.EditValue = userCreate.UserName;

                User userEdit = UserList.Instance.GetByID(_HoSoDangKy.CanBoSuaID);

                //                if (_HoSoDangKy.DiaBanID is int) cmbDonViCap.EditValue = _HoSoDangKy.DiaBanID;
                if (_HoSoDangKy.LoaiHoSoID is int) cmbLoaiHoSo.EditValue = _HoSoDangKy.LoaiHoSoID;
                txtTenCSKD.EditValue = _HoSoDangKy.TenCoSoKD;
                txtSoGiayPhep.EditValue = _HoSoDangKy.SoGiayPhepKD;
                txtCoQuanCap.EditValue = _HoSoDangKy.CoQuanCapKD;
                if (_HoSoDangKy.NgayCapCMND is DateTime?) dateNgayCap.EditValue = _HoSoDangKy.NgayCapCMND;
                else dateNgayCap.EditValue = null;
                txtToKhu.EditValue = _HoSoDangKy.DiaDiem_KD1;
                if (_HoSoDangKy.DiaDiem_KD2_DiaBanID is int) cmbPhuongXa.EditValue = _HoSoDangKy.DiaDiem_KD2_DiaBanID;

                txtTenChuCoSo.EditValue = _HoSoDangKy.ChuCoSo;
                if ((_HoSoDangKy.GioiTinh is bool?))
                {
                    if (_HoSoDangKy.GioiTinh == true)
                    {
                        rdoNam.Checked = true;
                        rdoNu.Checked = false;
                    }
                    else
                    {
                        rdoNam.Checked = false;
                        rdoNu.Checked = true;
                    }
                }
                else
                {
                    rdoNam.Checked = false;
                    rdoNu.Checked = false;
                }

                if (_HoSoDangKy.NgaySinh is DateTime?) dateNamSinh.EditValue = _HoSoDangKy.NgaySinh;
                else dateNamSinh.EditValue = null;
                txtCMND.Text = _HoSoDangKy.SoCMND;
                txtDonViCap.EditValue = _HoSoDangKy.DonViCap;
                if (_HoSoDangKy.DanTocID is int) cmbDanToc.EditValue = _HoSoDangKy.DanTocID;
                if (_HoSoDangKy.QuocTichID is int) cmbQuocTich.EditValue = _HoSoDangKy.QuocTichID;
                txtDienThoai.Text = _HoSoDangKy.DienThoai;
                txtHoKhau.EditValue = _HoSoDangKy.HK_ThuongTru;
                txtHienO.EditValue = _HoSoDangKy.HienO;
                if (_HoSoDangKy.MoHinhID is int) cmbMoHinhKD.EditValue = _HoSoDangKy.MoHinhID;
                if (_HoSoDangKy.NganhNgheID is int) cmbNganhNghe.EditValue = _HoSoDangKy.NganhNgheID;

                if (_HoSoDangKy.NgayCap is DateTime?) dateNgayCapGiayANTT.EditValue = _HoSoDangKy.NgayCap;
                else dateNgayCapGiayANTT.EditValue = null;
                txtNoiCapPCCC.EditValue = _HoSoDangKy.NoiCapPCCC;
                dsHoSo.QuyMoHoatDong.Clear();

                dsHoSo.PCCC.Clear();
                if (_HoSoDangKy.ID is int && _HoSoDangKy.TongSoCO2 is int && _HoSoDangKy.TongSoBinhBot is int && _HoSoDangKy.TongSoLangVoi is int &&
                    _HoSoDangKy.TongSoMayBom is int && _HoSoDangKy.TongSoNguoi is int)
                    dsHoSo.PCCC.Rows.Add(_HoSoDangKy.ID, _HoSoDangKy.TongSoCO2, _HoSoDangKy.TongSoBinhBot, _HoSoDangKy.TongSoLangVoi, _HoSoDangKy.TongSoMayBom, _HoSoDangKy.TongSoNguoi);

                txtGhiChu.EditValue = _HoSoDangKy.GhiChu;

                byte[] imageChuCoSo = new byte[0];
                if (_HoSoDangKy.AnhDaiDien is byte[]) imageChuCoSo = _HoSoDangKy.AnhDaiDien;
                MemoryStream stream = new MemoryStream(imageChuCoSo);
                if (stream.Length > 0) pictureBoxAnhHoSo.Image = Image.FromStream(stream);
                else pictureBoxAnhHoSo.Image = null;
                //Set the SizeMode to center the image.
                this.pictureBoxAnhHoSo.SizeMode = PictureBoxSizeMode.StretchImage;

                // Set the border style to a three-dimensional border.
                this.pictureBoxAnhHoSo.BorderStyle = BorderStyle.Fixed3D;
                LoadUpdateGridView();
            }
            catch (Exception ex)
            {
                GenaralLibs.FrmExceptionNotifier.ShowAndLog(ex);
            }
            nmrSTTHoSo.Focus();
        }

        protected void CreateNew()
        {
            _HoSoDangKy = DanhMucHoSoDangKy.Instance.NewDoiTuong();
            try
            {
                nmrSTTHoSo.Text = "";
                txtSoHoSo.EditValue = null;
                //txtCanBo.EditValue = null;
                txtCanBo.EditValue = User.CurUser.UserName;
                txtCanBo.Properties.ReadOnly = true;
                //cmbDonViCap.EditValue = null;
                cmbLoaiHoSo.EditValue = null;
                txtTenCSKD.EditValue = null;
                txtSoGiayPhep.EditValue = null;
                txtCoQuanCap.EditValue = null;
                dateNgayCap.EditValue = null;
                txtToKhu.EditValue = null;
                cmbPhuongXa.EditValue = null;
                txtTenChuCoSo.EditValue = null;

                rdoNam.Checked = false;
                rdoNu.Checked = false;

                dateNamSinh.EditValue = null;
                txtCMND.Text = "";
                txtDonViCap.EditValue = null;
                cmbDanToc.EditValue = null;
                cmbQuocTich.EditValue = null;
                txtDienThoai.Text = "";
                txtHoKhau.EditValue = null;
                txtHienO.EditValue = null;
                cmbMoHinhKD.EditValue = null;
                cmbNganhNghe.EditValue = null;

                dateNgayCapGiayANTT.EditValue = null;
                txtNoiCapPCCC.EditValue = null;
                dsHoSo.QuyMoHoatDong.Clear();
                dsHoSo.QuyMoHoatDong.Rows.Add(0, 0, 0, 0);

                dsHoSo.PCCC.Clear();
                dsHoSo.PCCC.Rows.Add(0, 0, 0, 0, 0, 0);

                SetEditState(EditState.CreatingNew);
            }
            catch (Exception ex)
            {
                GenaralLibs.FrmExceptionNotifier.ShowAndLog(ex);
            }
            nmrSTTHoSo.Focus();
        }

        protected void Save(EditState editStateForSave)
        {
            try
            {
                SqlConnection con = new SqlConnection(LocalSettings.ConnectString);
                SqlTransaction transaction = null;
                try
                {
                    con.Open();
                    transaction = con.BeginTransaction();

                    SqlCommand cmd = con.CreateCommand();
                    cmd.Transaction = transaction;
                    HoSoDangKy hsDKTemp = null;

                    if (_EditState == EditState.CreatingNew)
                    {
                        HoSoDangKy hsDKnew = null;
                        if (_HoSoDangKy == null)
                            hsDKnew = DanhMucHoSoDangKy.Instance.NewDoiTuong();
                        else
                            hsDKnew = _HoSoDangKy;

                        if (nmrSTTHoSo.Text != "") hsDKnew.SoTT = Convert.ToInt32(nmrSTTHoSo.Text);
                        hsDKnew.SoHoSo = txtSoHoSo.Text.Trim();
                        //hsDKnew.CanBoCapID = txtCanBo.Text.Trim();
                        hsDKnew.CanBoCapID = User.CurUser.ID;
                        hsDKnew.CanBoSuaID = 0;

                        //if (cmbDonViCap.EditValue is int) hsDKnew.DiaBanID = (int)cmbDonViCap.EditValue;
                        if (cmbLoaiHoSo.EditValue is int) hsDKnew.LoaiHoSoID = (int)cmbLoaiHoSo.EditValue;
                        hsDKnew.TenCoSoKD = txtTenCSKD.Text.Trim();
                        hsDKnew.SoGiayPhepKD = txtSoGiayPhep.Text.Trim();
                        hsDKnew.CoQuanCapKD = txtCoQuanCap.Text.Trim();
                        if (dateNgayCap.EditValue != null) hsDKnew.NgayCapCMND = dateNgayCap.DateTime;
                        hsDKnew.DiaDiem_KD1 = txtToKhu.Text.Trim();
                        if (cmbPhuongXa.EditValue is int) hsDKnew.DiaDiem_KD2_DiaBanID = (int)cmbPhuongXa.EditValue;
                        hsDKnew.ChuCoSo = txtTenChuCoSo.Text.Trim();
                        if (rdoNam.Checked) hsDKnew.GioiTinh = true;
                        else if (rdoNu.Checked) hsDKnew.GioiTinh = false;

                        if (dateNamSinh.EditValue != null)
                        {
                            hsDKnew.NgaySinh = dateNamSinh.DateTime;
                            hsDKnew.NamSinh = dateNamSinh.DateTime.Year;
                        }

                        hsDKnew.SoCMND = txtCMND.Text.Trim();
                        hsDKnew.DonViCap = txtDonViCap.Text.Trim();
                        if (cmbDanToc.EditValue is int) hsDKnew.DanTocID = (int)cmbDanToc.EditValue;
                        if (cmbQuocTich.EditValue is int) hsDKnew.QuocTichID = (int)cmbQuocTich.EditValue;
                        hsDKnew.DienThoai = txtDienThoai.Text.Trim();
                        hsDKnew.HK_ThuongTru = txtHoKhau.Text.Trim();
                        hsDKnew.HienO = txtHienO.Text.Trim();
                        if (cmbMoHinhKD.EditValue is int) hsDKnew.MoHinhID = (int)cmbMoHinhKD.EditValue;
                        if (cmbNganhNghe.EditValue is int) hsDKnew.NganhNgheID = (int)cmbNganhNghe.EditValue;

                        hsDKnew.NoiCapPCCC = txtNoiCapPCCC.Text.Trim();

                        if (gridViewPCCC.DataSource is DataView && (gridViewPCCC.DataSource as DataView).Count > 0)
                        {
                            DataRow rowPCCC = (gridViewPCCC.DataSource as DataView).ToTable().Rows[0];
                            hsDKnew.TongSoCO2 = (int)rowPCCC["TongSoCO2"];
                            hsDKnew.TongSoBinhBot = (int)rowPCCC["TongSoBinhBot"];
                            hsDKnew.TongSoLangVoi = (int)rowPCCC["TongSoLangVoi"];
                            hsDKnew.TongSoMayBom = (int)rowPCCC["TongSoMayBom"];
                            hsDKnew.TongSoNguoi = (int)rowPCCC["TongSoNguoi"];
                        }
                        if (dateNgayCapGiayANTT.EditValue != null) hsDKnew.NgayCap = dateNgayCapGiayANTT.DateTime;
                        hsDKnew.TrangThaiHS = (int)editStateForSave;
                        hsDKnew.GhiChu = txtGhiChu.Text;

                        MemoryStream stream = new MemoryStream();
                        if (pictureBoxAnhHoSo.Image != null)
                            pictureBoxAnhHoSo.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                        byte[] pic = stream.ToArray();

                        hsDKnew.AnhDaiDien = pic;

                        hsDKnew.InsertToDB();
                        hsDKTemp = hsDKnew;
                    }
                    else if (_EditState == EditState.Modifying)
                    {
                        HoSoDangKy hsDK = DanhMucHoSoDangKy.Instance.GetByID(_HoSoDangKy.ID);

                        if (nmrSTTHoSo.Text != "") hsDK.SoTT = Convert.ToInt32(nmrSTTHoSo.Text);
                        hsDK.SoHoSo = txtSoHoSo.Text.Trim();
                        hsDK.CanBoCapID = _HoSoDangKy.CanBoCapID;
                        hsDK.CanBoSuaID = User.CurUser.ID;
                        hsDK.ThoiGianSua = DateTime.Now;
                        //if (cmbDonViCap.EditValue is int) hsDK.DiaBanID = (int)cmbDonViCap.EditValue;
                        if (cmbLoaiHoSo.EditValue is int) hsDK.LoaiHoSoID = (int)cmbLoaiHoSo.EditValue;
                        hsDK.TenCoSoKD = txtTenCSKD.Text.Trim();
                        hsDK.SoGiayPhepKD = txtSoGiayPhep.Text.Trim();
                        hsDK.CoQuanCapKD = txtCoQuanCap.Text.Trim();
                        if (dateNgayCap.EditValue != null) hsDK.NgayCapCMND = dateNgayCap.DateTime;
                        hsDK.DiaDiem_KD1 = txtToKhu.Text.Trim();
                        if (cmbPhuongXa.EditValue is int) hsDK.DiaDiem_KD2_DiaBanID = (int)cmbPhuongXa.EditValue;
                        hsDK.ChuCoSo = txtTenChuCoSo.Text.Trim();
                        if (rdoNam.Checked) hsDK.GioiTinh = true;
                        else if (rdoNu.Checked) hsDK.GioiTinh = false;

                        if (dateNamSinh.EditValue != null)
                        {
                            hsDK.NgaySinh = dateNamSinh.DateTime;
                            hsDK.NamSinh = dateNamSinh.DateTime.Year;
                        }

                        hsDK.SoCMND = txtCMND.Text.Trim();
                        hsDK.DonViCap = txtDonViCap.Text.Trim();
                        if (cmbDanToc.EditValue is int) hsDK.DanTocID = (int)cmbDanToc.EditValue;
                        if (cmbQuocTich.EditValue is int) hsDK.QuocTichID = (int)cmbQuocTich.EditValue;
                        hsDK.DienThoai = txtDienThoai.Text.Trim();
                        hsDK.HK_ThuongTru = txtHoKhau.Text.Trim();
                        hsDK.HienO = txtHienO.Text.Trim();
                        if (cmbMoHinhKD.EditValue is int) hsDK.MoHinhID = (int)cmbMoHinhKD.EditValue;
                        if (cmbNganhNghe.EditValue is int) hsDK.NganhNgheID = (int)cmbNganhNghe.EditValue;

                        hsDK.NoiCapPCCC = txtNoiCapPCCC.Text.Trim();

                        if (gridViewPCCC.DataSource is DataView && (gridViewPCCC.DataSource as DataView).Count > 0)
                        {
                            DataRow rowPCCC = (gridViewPCCC.DataSource as DataView).ToTable().Rows[0];
                            hsDK.TongSoCO2 = (int)rowPCCC["TongSoCO2"];
                            hsDK.TongSoBinhBot = (int)rowPCCC["TongSoBinhBot"];
                            hsDK.TongSoLangVoi = (int)rowPCCC["TongSoLangVoi"];
                            hsDK.TongSoMayBom = (int)rowPCCC["TongSoMayBom"];
                            hsDK.TongSoNguoi = (int)rowPCCC["TongSoNguoi"];
                        }
                        if (dateNgayCapGiayANTT.EditValue != null) hsDK.NgayCap = dateNgayCapGiayANTT.DateTime;
                        hsDK.TrangThaiHS = (int)editStateForSave;
                        hsDK.GhiChu = txtGhiChu.Text;

                        MemoryStream stream = new MemoryStream();
                        if (pictureBoxAnhHoSo.Image != null)
                            pictureBoxAnhHoSo.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                        byte[] pic = stream.ToArray();
                        hsDK.AnhDaiDien = pic;

                        hsDK.UpdateToDB();

                        User userEdit = UserList.Instance.GetByID(hsDK.CanBoSuaID);
                        hsDKTemp = hsDK;
                    }

                    //PH
                    //Cho Số CMND và Số GPKD
                    //Số CMND 
                    HoSoCMND hsCMND = DanhMucHoSoCMND.Instance.GetBySoCMND(txtCMND.Text.Trim());
                    if (txtCMND.Text != "")
                    {
                        if (hsCMND == null)
                        {
                            hsCMND = DanhMucHoSoCMND.Instance.NewDoiTuong();

                            hsCMND.HoTen = txtTenChuCoSo.Text.Trim();
                            MemoryStream stream = new MemoryStream();
                            if (pictureBoxAnhHoSo.Image != null)
                                pictureBoxAnhHoSo.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                            byte[] pic = stream.ToArray();
                            hsCMND.AnhDaiDien = pic;
                            if (rdoNam.Checked) hsCMND.GioiTinh = true;
                            else if (rdoNu.Checked) hsCMND.GioiTinh = false;

                            if (dateNamSinh.EditValue != null) hsCMND.NgaySinh = dateNamSinh.DateTime;
                            hsCMND.SoCMND = txtCMND.Text.Trim();
                            hsCMND.DonViCap = txtDonViCap.Text.Trim();
                            if (cmbDanToc.EditValue is int) hsCMND.DanTocID = (int)cmbDanToc.EditValue;
                            if (cmbQuocTich.EditValue is int) hsCMND.QuocTichID = (int)cmbQuocTich.EditValue;
                            hsCMND.HK_ThuongTru = txtHoKhau.Text.Trim();
                            hsCMND.DiaChi = txtHienO.Text.Trim();

                            hsCMND.InsertToDB();
                        }
                        else
                        {
                            hsCMND.HoTen = txtTenChuCoSo.Text.Trim();
                            MemoryStream stream = new MemoryStream();
                            if (pictureBoxAnhHoSo.Image != null)
                                pictureBoxAnhHoSo.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                            byte[] pic = stream.ToArray();
                            hsCMND.AnhDaiDien = pic;
                            if (rdoNam.Checked) hsCMND.GioiTinh = true;
                            else if (rdoNu.Checked) hsCMND.GioiTinh = false;

                            if (dateNamSinh.EditValue != null) hsCMND.NgaySinh = dateNamSinh.DateTime;
                            hsCMND.SoCMND = txtCMND.Text.Trim();
                            hsCMND.DonViCap = txtDonViCap.Text.Trim();
                            if (cmbDanToc.EditValue is int) hsCMND.DanTocID = (int)cmbDanToc.EditValue;
                            if (cmbQuocTich.EditValue is int) hsCMND.QuocTichID = (int)cmbQuocTich.EditValue;
                            hsCMND.HK_ThuongTru = txtHoKhau.Text.Trim();
                            hsCMND.DiaChi = txtHienO.Text.Trim();

                            hsCMND.UpdateToDB();
                        }
                    }
                    //Số GPKD
                    HoSoDKKD hsDKKD = DanhMucHoSoDKKD.Instance.GetBySoGiayPhep(txtSoGiayPhep.Text.Trim());
                    if (txtSoGiayPhep.Text != "")
                    {
                        if (hsDKKD == null && txtCMND.Text != "")
                        {
                            hsDKKD = DanhMucHoSoDKKD.Instance.NewDoiTuong();

                            hsDKKD.ChuCoSo = txtTenChuCoSo.Text.Trim();
                            hsDKKD.SoCMND = txtCMND.Text.Trim();
                            hsDKKD.SoGiayPhep = txtSoGiayPhep.Text.Trim();
                            hsDKKD.CoQuanCap = txtCoQuanCap.Text.Trim();
                            if (dateNgayCap.EditValue != null) hsDKKD.NgayCapPhep = dateNgayCap.DateTime;
                            hsDKKD.DiaDiem_KD1 = txtToKhu.Text.Trim();
                            if (cmbPhuongXa.EditValue is int) hsDKKD.DiaDiem_KD2 = (int)cmbPhuongXa.EditValue;

                            hsDKKD.InsertToDB();
                        }
                        else
                        {
                            hsDKKD.ChuCoSo = txtTenChuCoSo.Text.Trim();
                            hsDKKD.SoCMND = txtCMND.Text.Trim();
                            hsDKKD.SoGiayPhep = txtSoGiayPhep.Text.Trim();
                            hsDKKD.CoQuanCap = txtCoQuanCap.Text.Trim();
                            if (dateNgayCap.EditValue != null) hsDKKD.NgayCapPhep = dateNgayCap.DateTime;
                            hsDKKD.DiaDiem_KD1 = txtToKhu.Text.Trim();
                            if (cmbPhuongXa.EditValue is int) hsDKKD.DiaDiem_KD2 = (int)cmbPhuongXa.EditValue;

                            hsDKKD.UpdateToDB();
                        }
                    }

                    SetEditState(editStateForSave);
                    DanhMucHoSoDangKy.Instance.LoadFromDB();
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    throw new Exception(ex.Message);
                }
                finally
                {
                    con.Close();
                }
            }
            catch (Exception ex)
            {
                GenaralLibs.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        protected void Delete()
        {
            try
            {
                //if (MessageBox.Show("Bạn có thực sự muốn xóa?", "Xác nhận", MessageBoxButtons.YesNo) == DialogResult.No)
                //{
                //    return;
                //}
            }
            catch (Exception ex)
            {
                GenaralLibs.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        protected bool CheckFullInfo()
        {
            //if (cmbDonViCap.EditValue == null || (int)cmbDonViCap.EditValue <= 0)
            //{
            //    throw new CustomException("Hãy chọn đơn vị cấp", ExceptionType.LackOfInputInfo);
            //}
            if (cmbLoaiHoSo.EditValue == null || (int)cmbLoaiHoSo.EditValue <= 0)
            {
                throw new CustomException("Hãy chọn phân loại", ExceptionType.LackOfInputInfo);
            }
            if (txtCanBo.Text == "")
            {
                throw new CustomException("Hãy nhập tên cán bộ nhập");
                return false;
            }
            if (txtTenCSKD.Text == "")
            {
                throw new CustomException("Hãy nhập tên cơ sở kinh doanh");
                return false;
            }
            if (nmrSTTHoSo.Text == "")
            {
                throw new CustomException("Hãy nhập số thứ tự của hồ sơ");
                return false;
            }
            if (txtSoHoSo.Text == "")
            {
                throw new CustomException("Hãy nhập số hồ sơ");
                return false;
            }
            if (txtCoQuanCap.Text == "")
            {
                throw new CustomException("Hãy nhập cơ quan gấp");
                return false;
            }
            if (txtTenChuCoSo.Text == "")
            {
                throw new CustomException("Hãy nhập tên chủ cơ sở");
                return false;
            }
            if (txtSoGiayPhep.Text == "")
            {
                throw new CustomException("Hãy nhập số giấy phép");
                return false;
            }
            if (txtToKhu.Text == "")
            {
                throw new CustomException("Hãy nhập tổ khu");
                return false;
            }
            if (cmbPhuongXa.EditValue == null || (int)cmbPhuongXa.EditValue <= 0)
            {
                throw new CustomException("Hãy nhập phường xã", ExceptionType.LackOfInputInfo);
            }
            if (dateNgayCap.Text == "")
            {
                throw new CustomException("Hãy nhập ngày cấp");
                return false;
            }
            if (dateNamSinh.Text == "")
            {
                throw new CustomException("Hãy nhập năm sinh");
                return false;
            }
            if (txtCMND.Text == "")
            {
                throw new CustomException("Hãy nhập CMND");
                return false;
            }
            if (txtDonViCap.Text == "")
            {
                throw new CustomException("Hãy nhập Đơn vị cấp");
                return false;
            }
            if (cmbDanToc.EditValue == null || (int)cmbDanToc.EditValue <= 0)
            {
                throw new CustomException("Hãy chọn dân tộc", ExceptionType.LackOfInputInfo);
            }
            if (cmbQuocTich.EditValue == null || (int)cmbQuocTich.EditValue <= 0)
            {
                throw new CustomException("Hãy chọn quốc tịch", ExceptionType.LackOfInputInfo);
            }
            if (txtDienThoai.Text == "")
            {
                throw new CustomException("Hãy nhập số điện thoại");
                return false;
            }
            if (txtHoKhau.Text == "")
            {
                throw new CustomException("Hãy nhập hộ khẩu");
                return false;
            }
            if (txtHienO.Text == "")
            {
                throw new CustomException("Hãy nhập hiện nay ở đâu?");
                return false;
            }
            if (txtNoiCapPCCC.Text == "")
            {
                throw new CustomException("Hãy nhập nơi cấp PCCC");
                return false;
            }
            if (dateNgayCapGiayANTT.Text == "")
            {
                throw new CustomException("Hãy nhập ngày cấp giấy ANTT");
                return false;
            }
            if (rdoNam.Checked == false && rdoNu.Checked == false)
            {
                throw new CustomException("Hãy chọn giới tính");
                return false;
            }

            return true;
        }

        private void FrmHoSoKemTieuThuc_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;
            dsHoSo.PCCC.RowChanged += new DataRowChangeEventHandler(PCCC_RowChanged);

            webcam = new WebCam();
            webcam.InitializeWebCam(ref pictureBoxAnhHoSo);

            #region cmbPhuongXa
            cmbPhuongXa.DataSource = DanhMucDiaBan.Instance.DataView;
            cmbPhuongXa.DisplayColumn = "TenDiaBan";
            cmbPhuongXa.ValueColumn = "ID";
            cmbPhuongXa.AddVisibleColumn("ID", "Mã");
            cmbPhuongXa.AddVisibleColumn("TenDiaBan", "Tên địa bàn");
            cmbPhuongXa.AddVisibleColumn("TenTat", "Tên viết tắt");
            #endregion

           

            #region cmbLoaiHoSo
            cmbLoaiHoSo.DataSource = DanhMucLoaiHoSo.Instance.DataView;
            cmbLoaiHoSo.DisplayColumn = "TenLoai";
            cmbLoaiHoSo.ValueColumn = "ID";
            cmbLoaiHoSo.AddVisibleColumn("ID", "Mã");
            cmbLoaiHoSo.AddVisibleColumn("TenLoai", "Tên loại");
            #endregion

            #region cmbNganhNghe
            cmbNganhNghe.DataSource = DanhMucNganhNghe.Instance.DataView;
            cmbNganhNghe.DisplayColumn = "TenNganhNghe";
            cmbNganhNghe.ValueColumn = "ID";
            cmbNganhNghe.AddVisibleColumn("ID", "Mã");
            cmbNganhNghe.AddVisibleColumn("TenNganhNghe", "Tên ngành nghề");
            #endregion

            #region cmbDanToc
            cmbDanToc.DataSource = DanhMucDanToc.Instance.DataView;
            cmbDanToc.DisplayColumn = "TenDanToc";
            cmbDanToc.ValueColumn = "ID";
            cmbDanToc.AddVisibleColumn("ID", "Mã");
            cmbDanToc.AddVisibleColumn("TenDanToc", "Tên loại");
            #endregion

            #region cmbQuocTich
            cmbQuocTich.DataSource = DanhMucQuocTich.Instance.DataView;
            cmbQuocTich.DisplayColumn = "TenQuocTich";
            cmbQuocTich.ValueColumn = "ID";
            cmbQuocTich.AddVisibleColumn("ID", "Mã");
            cmbQuocTich.AddVisibleColumn("TenQuocTich", "Tên quốc tịch");
            #endregion

            #region cmbMoHinhKD
            cmbMoHinhKD.DataSource = DanhMucMoHinhKD.Instance.DataView;
            cmbMoHinhKD.DisplayColumn = "MoHinhKD";
            cmbMoHinhKD.ValueColumn = "ID";
            cmbMoHinhKD.AddVisibleColumn("ID", "Mã");
            cmbMoHinhKD.AddVisibleColumn("MoHinhKD", "Tên mô hình kinh doanh");
            #endregion

            if (Config.DonViCap is int && Config.NamQuanLy is int)
            {
                DMDiaBan diaBan = DanhMucDiaBan.Instance.GetByID(Config.DonViCap);
                if (diaBan != null)
                    lblTitle.Text = string.Format("({0}-{1})", DanhMucDiaBan.Instance.GetByID(Config.DonViCap).TenDiaBan, Config.NamQuanLy);
            }


            gridControlPCCC.DataSource = dsHoSo.PCCC;

            //DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repLookupTrangThaiHS = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
            //repLookupTrangThaiHS.DataSource = TrangThaiHoSo.DTTrangThai();
            //repLookupTrangThaiHS.ValueMember = "MaTrangThai";
            //repLookupTrangThaiHS.DisplayMember = "TenTrangThai";

            //colTrangThaiHS.FieldName = "TrangThaiHS";
            //colTrangThaiHS.ColumnEdit = repLookupTrangThaiHS;
            //colTrangThaiHS.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

           
            FormatNumberInGridView(gridView1);
            FormatNumberInGridView(gridViewDs);
            SetEditState(EditState.LuuTam);

            nmrSTTHoSo.Focus();
        }

        void PCCC_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            gridViewPCCC.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.None;
        }

        private void btnThem_Click(object sender, EventArgs e)
        {
            CreateNew();
            dateNgayCapGiayANTT.EditValue = DateTime.Now;
        }

        private void btnGhi_Click(object sender, EventArgs e)
        {
            try
            {
                Save(EditState.LuuTam);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnLuuGoc_Click(object sender, EventArgs e)
        {
            try
            {
                CheckFullInfo();
                Save(EditState.LuuGoc);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void txtDienThoai_TextChanged(object sender, EventArgs e)
        {

        }

        //PH
        private string GetSoHoSoLatest()
        {
            SqlConnection con = new SqlConnection(LocalSettings.ConnectString);
            string soHoSoLatest = "";
            DMDiaBan diaBan = DanhMucDiaBan.Instance.GetByID(Config.DonViCap);

            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandText = string.Format("SELECT TOP 1 * FROM HoSoDangKy \n" +
                                                "ORDER BY ID DESC");
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = cmd;
                DataTable dt = new DataTable();
                da.Fill(dt);
                if (dt != null && dt.Rows.Count > 0)
                {
                    soHoSoLatest = dt.Rows[0]["SoHoSo"].ToString();
                }
                else
                {
                    //Chưa có hóa đơn nào return về số đầu tiên được cấp - 1
                    //return (diaBan.TuSo - 1).ToString();
                    return "";
                }
            }
            catch (Exception ex)
            {
                GenaralLibs.FrmExceptionNotifier.ShowAndLog(ex);
                return "";
            }
            finally
            {
                con.Close();
            }
            return soHoSoLatest;
        }
        private string GetSoHoSo(int phanLoai)
        {
            //if (_EditState != EditState.CreatingNew) return;

            if (phanLoai == 3) return ""; //Nếu là nhập dữ liệu thì không cần sinh số

            DMDiaBan diaBan = DanhMucDiaBan.Instance.GetByID(Config.DonViCap);
            string soHoSo = "";
            soHoSo = GetSoHoSoLatest();
            string[] temp = soHoSo.Split('/');// Số hồ sơ bao giờ cũng có cái gạch này để phân cách. Dựa vào nó để tách số là hợp lý
            int so = 0;

            so = Convert.ToInt32(temp[0]);
            int a = Config.TuSo;
            int b = Config.DenSo;
            so++;

            //if ((so < Config.TuSo || Config.DenSo < so) && so != 0)
            if ((so < a || b < so) && so != 0)
                throw new Exception("Dải số hồ sơ chưa được cấp hoặc đã hết sử dụng hết");

            switch (so.ToString())
            {
                case "1":
                case "2":
                case "3":
                case "4":
                case "5":
                case "6":
                case "7":
                case "8":
                case "9":
                    temp[0] = "0" + so.ToString();
                    break;
                default:
                    temp[0] = so.ToString();
                    break;
            }

            soHoSo = string.Format("{0}/XN-{1}", temp[0], Config.TenVietTat);
            return soHoSo;
        }
        //PH

        private void btnChupAnh_Click(object sender, EventArgs e)
        {
            FrmWebcam frm = new FrmWebcam();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                pictureBoxAnhHoSo.Image = frm.imgCapture.Image;
            }
        }
        private void btnMoAnhBangDuongDan_Click(object sender, EventArgs e)
        {
            ////lọc những đuôi ảnh 
            //openFileDialogImage.Filter = "Image Files(*.bmp;*.jpg;*.gif;*.png;*.ico)| (*.bmp;*.jpg;*.gif;*.png;*.ico)";
            ////thiết lặp đường dẫn mặc định, và có khả năng nhớ đường dẫn
            //openFileDialogImage.InitialDirectory = (Application.ExecutablePath);
            //openFileDialogImage.Title = "Mở File Ảnh";
            //if (openFileDialogImage.ShowDialog() == DialogResult.OK)
            //{
            //    //load ảnh vừa chọn lên picturebox
            //    pictureBoxAnhHoSo.Image = new Bitmap(openFileDialogImage.OpenFile());
            //}
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Title = " Open file...";
            openFileDialog1.InitialDirectory = "D:\\";
            openFileDialog1.Filter = " Image file (*.BMP,*.JPG,*.JPEG)|*.bmp;*.jpg;*.jpeg ";
            openFileDialog1.FileName = "";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
                pictureBoxAnhHoSo.Image = Image.FromFile(openFileDialog1.FileName);

            //Set the SizeMode to center the image.
            this.pictureBoxAnhHoSo.SizeMode = PictureBoxSizeMode.StretchImage;

            // Set the border style to a three-dimensional border.
            this.pictureBoxAnhHoSo.BorderStyle = BorderStyle.Fixed3D;
        }
        private void btnXoa_Click(object sender, EventArgs e)
        {
            try
            {
                if (_EditState != EditState.Modifying)  //Xóa 1 hàng từ Grid
                {
                    DataRow row = gridViewDs.GetFocusedDataRow();
                    _HoSoDangKy = DanhMucHoSoDangKy.Instance.GetByID((int)row["ID"]);
                }
                else  //Xóa hàng đang sửa
                {
                    //_HoSoDangKy chứa hồ sơ đang sửa. Xóa là xóa ông này
                }
                if (MessageBox.Show("Bạn có thực sự muốn xóa?", "Cảnh báo", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    _HoSoDangKy.DeleteFromDB();
                    _HoSoDangKy = null;
                    SetEditState(EditState.LuuTam);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void btnSua_Click(object sender, EventArgs e)
        {
            Edit();
        }
        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtNoiDungViPham_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            
        }

        private void txtNoiDungViPham_MouseClick(object sender, MouseEventArgs e)
        {
            
        }

        private void gridControlDs_MouseClick(object sender, MouseEventArgs e)
        {
            Edit();
        }

        private void dateNgayBatDau_EditValueChanged(object sender, EventArgs e)
        {
        }

        private void dateNgayKetThuc_EditValueChanged(object sender, EventArgs e)
        {
        }

        private void cmbLocTrangThai_EditValueChanged(object sender, EventArgs e)
        {
        }
        private void LoadGirdView()
        {
            gridControNganhNgheTieuThuc.BeginUpdate();
            gridControNganhNgheTieuThuc.DataSource = DanhMucTieuThucQuanLy.Instance.GetByNganhNgheID(Convert.ToInt32(cmbNganhNghe.EditValue.ToString())).DefaultView;
            gridControNganhNgheTieuThuc.MainView.PopulateColumns();
            gridControNganhNgheTieuThuc.EndUpdate();
        }
        private void LoadUpdateGridView()
        {
            gridControNganhNgheTieuThuc.BeginUpdate();
            gridControNganhNgheTieuThuc.DataSource = DanhMucGiaTriTieuThuc.Instance.LoadByNganhNgheID(Convert.ToInt32(cmbNganhNghe.EditValue.ToString()), _HoSoDangKy.ID).DefaultView;
            gridControNganhNgheTieuThuc.MainView.PopulateColumns();
            gridControNganhNgheTieuThuc.EndUpdate();
        }

        #region Quản lý file

        private void btnQuanLyFile_Click(object sender, EventArgs e)
        {
            if (_EditState == EditState.CreatingNew || _EditState == EditState.Modifying)
            {
                FrmQuanLyFile frm = null;
                if (cmbNganhNghe.EditValue != null && cmbNganhNghe.EditValue is int)
                {
                    frm = new FrmQuanLyFile(_HoSoDangKy, (int)cmbNganhNghe.EditValue);
                    if (frm.ShowDialog() == DialogResult.OK)
                    {
                    }
                }
                else
                {
                    MessageBox.Show("Chưa chọn ngành nghề");
                }
            }
        }
        #endregion

        //PH
        private void cmbLoaiHoSo_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                if (_EditState != EditState.CreatingNew) return;

                if (cmbLoaiHoSo.EditValue != null && cmbLoaiHoSo.EditValue is int)
                    txtSoHoSo.EditValue = GetSoHoSo((int)cmbLoaiHoSo.EditValue);
            }
            catch (Exception ex)
            {
                GenaralLibs.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }
        private void btnCheckCMND_Click(object sender, EventArgs e)
        {
            HoSoCMND hsCMND = DanhMucHoSoCMND.Instance.GetBySoCMND(txtCMND.Text.Trim());
            if (hsCMND != null)
            {
                txtTenChuCoSo.EditValue = hsCMND.HoTen;
                if ((hsCMND.GioiTinh is bool?))
                {
                    if (hsCMND.GioiTinh == true)
                    {
                        rdoNam.Checked = true;
                        rdoNu.Checked = false;
                    }
                    else
                    {
                        rdoNam.Checked = false;
                        rdoNu.Checked = true;
                    }
                }
                else
                {
                    rdoNam.Checked = false;
                    rdoNu.Checked = false;
                }

                if (hsCMND.NgaySinh is DateTime?) dateNamSinh.EditValue = hsCMND.NgaySinh;
                else dateNamSinh.EditValue = null;
                txtDonViCap.EditValue = hsCMND.DonViCap;
                if (hsCMND.DanTocID is int) cmbDanToc.EditValue = hsCMND.DanTocID;
                if (hsCMND.QuocTichID is int) cmbQuocTich.EditValue = hsCMND.QuocTichID;
                txtHoKhau.EditValue = hsCMND.HK_ThuongTru;
                txtHienO.EditValue = hsCMND.DiaChi;

                byte[] imageChuCoSo = new byte[0];
                if (hsCMND.AnhDaiDien is byte[]) imageChuCoSo = hsCMND.AnhDaiDien;
                MemoryStream stream = new MemoryStream(imageChuCoSo);
                if (stream.Length > 0) pictureBoxAnhHoSo.Image = Image.FromStream(stream);
                else pictureBoxAnhHoSo.Image = null;
                //Set the SizeMode to center the image.
                this.pictureBoxAnhHoSo.SizeMode = PictureBoxSizeMode.StretchImage;

                // Set the border style to a three-dimensional border.
                this.pictureBoxAnhHoSo.BorderStyle = BorderStyle.Fixed3D;
            }
        }
        private void btnCheckGPKD_Click(object sender, EventArgs e)
        {
            HoSoDKKD hsDKKD = DanhMucHoSoDKKD.Instance.GetBySoGiayPhep(txtSoGiayPhep.Text.Trim());

            if (hsDKKD != null)
            {
                txtTenChuCoSo.Text = hsDKKD.ChuCoSo;
                txtCMND.Text = hsDKKD.SoCMND;
                txtSoGiayPhep.Text = hsDKKD.SoGiayPhep;
                txtCoQuanCap.Text = hsDKKD.CoQuanCap;
                if (_HoSoDangKy.NgayCapCMND is DateTime?) dateNgayCap.EditValue = _HoSoDangKy.NgayCapCMND;

                txtToKhu.Text = hsDKKD.DiaDiem_KD1;
                cmbPhuongXa.EditValue = hsDKKD.DiaDiem_KD2;
            }
        }

        private void cmbNganhNghe_EditValueChanged(object sender, EventArgs e)
        {
            LoadGirdView();
        }
        //PH
        //PH nhớ thay REGEX tên viết hoa
    }
}





